package com.eshop.modules.activity.service.impl;

import org.springframework.context.ApplicationEvent;
import com.eshop.event.TemplateEvent;
import com.eshop.event.TemplateListenEnum;
import com.eshop.event.TemplateBean;
import java.util.Date;
import java.io.Serializable;
import com.eshop.enums.ShopCommonEnum;
import com.eshop.exception.BadRequestException;
import java.io.IOException;
import java.util.Iterator;
import com.eshop.utils.FileUtil;
import java.util.ArrayList;
import javax.servlet.http.HttpServletResponse;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.eshop.common.utils.QueryHelpPlus;
import com.eshop.modules.activity.service.dto.UserExtractDto;
import java.util.LinkedHashMap;
import java.util.List;
import com.github.pagehelper.PageInfo;
import java.util.Map;
import org.springframework.data.domain.Pageable;
import com.eshop.modules.activity.service.dto.UserExtractQueryCriteria;
import com.eshop.enums.BillDetailEnum;
import com.eshop.enums.PayTypeEnum;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.NumberUtil;
import com.eshop.api.EshopException;
import java.math.BigDecimal;
import com.eshop.modules.activity.param.UserExtParam;
import com.eshop.modules.user.domain.ShopUser;
import org.springframework.context.ApplicationEventPublisher;
import com.eshop.modules.user.service.UserBillService;
import com.eshop.modules.user.service.UserService;
import com.eshop.dozer.service.IGenerator;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Service;
import com.eshop.modules.activity.service.UserExtractService;
import com.eshop.modules.activity.domain.UserExtract;
import com.eshop.modules.activity.service.mapper.UserExtractMapper;
import com.eshop.common.service.impl.BaseServiceImpl;

@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = { Exception.class })
public class UserExtractServiceImpl extends BaseServiceImpl<UserExtractMapper, UserExtract> implements UserExtractService
{
    private final IGenerator generator;
    private final UserExtractMapper userExtractMapper;
    private final UserService userService;
    private final UserBillService billService;
    private final ApplicationEventPublisher publisher;
    
    @Transactional(rollbackFor = { Exception.class })
    public void userExtract(final ShopUser userInfo, final UserExtParam param) {
        final BigDecimal extractPrice = userInfo.getBrokeragePrice();
        if (extractPrice.compareTo(BigDecimal.ZERO) <= 0) {
            throw new EshopException("提现佣金不足");
        }
        final double money = Double.valueOf(param.getMoney());
        if (extractPrice.compareTo(BigDecimal.valueOf(money)) < 0) {
            throw new EshopException("提现佣金不足");
        }
        if (money <= 0.0) {
            throw new EshopException("提现佣金大于0");
        }
        double balance = NumberUtil.sub(extractPrice.doubleValue(), money);
        if (balance < 0.0) {
            balance = 0.0;
        }
        final UserExtract userExtract = new UserExtract();
        userExtract.setUid(userInfo.getUid());
        userExtract.setExtractType(param.getExtractType());
        userExtract.setExtractPrice(new BigDecimal(param.getMoney()));
        userExtract.setBalance(BigDecimal.valueOf(balance));
        if (StrUtil.isNotEmpty((CharSequence)param.getName())) {
            userExtract.setRealName(param.getName());
        }
        else {
            userExtract.setRealName(userInfo.getNickname());
        }
        if (StrUtil.isNotEmpty((CharSequence)param.getWeixin())) {
            userExtract.setWechat(param.getWeixin());
        }
        else {
            userExtract.setWechat(userInfo.getNickname());
        }
        String mark = "";
        if (PayTypeEnum.ALI.getValue().equals(param.getExtractType())) {
            if (StrUtil.isEmpty((CharSequence)param.getAlipayCode())) {
                throw new EshopException("请输入支付宝账号");
            }
            userExtract.setAlipayCode(param.getAlipayCode());
            mark = "使用支付宝提现" + param.getMoney() + "元";
        }
        else if (PayTypeEnum.WEIXIN.getValue().equals(param.getExtractType())) {
            if (StrUtil.isEmpty((CharSequence)param.getWeixin())) {
                throw new EshopException("请输入微信账号");
            }
            mark = "使用微信提现" + param.getMoney() + "元";
        }
        this.userExtractMapper.insert(userExtract);
        final ShopUser shopUser = new ShopUser();
        shopUser.setBrokeragePrice(BigDecimal.valueOf(balance));
        shopUser.setUid(userInfo.getUid());
        this.userService.updateById(shopUser);
        this.billService.expend(userInfo.getUid(), "佣金提现", BillDetailEnum.CATEGORY_1.getValue(), BillDetailEnum.TYPE_4.getValue(), money, balance, mark);
    }
    
    public double extractSum(final Long uid) {
        return this.userExtractMapper.sumPrice(uid);
    }
    
    public Map<String, Object> queryAll(final UserExtractQueryCriteria criteria, final Pageable pageable) {
        this.getPage(pageable);
        final PageInfo<UserExtract> page = (PageInfo<UserExtract>)new PageInfo((List)this.queryAll(criteria));
        final Map<String, Object> map = new LinkedHashMap<String, Object>(2);
        map.put("content", this.generator.convert(page.getList(), (Class)UserExtractDto.class));
        map.put("totalElements", page.getTotal());
        return map;
    }
    
    public List<UserExtract> queryAll(final UserExtractQueryCriteria criteria) {
        return (List<UserExtract>)((UserExtractMapper)this.baseMapper).selectList((Wrapper)QueryHelpPlus.getPredicate(UserExtract.class, criteria));
    }
    
    public void download(final List<UserExtractDto> all, final HttpServletResponse response) throws IOException {
        final List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        for (final UserExtractDto yxUserExtract : all) {
            final Map<String, Object> map = new LinkedHashMap<String, Object>();
            map.put(" uid", yxUserExtract.getUid());
            map.put("名称", yxUserExtract.getRealName());
            map.put("bank = 银行卡 alipay = 支付宝wx=微信", yxUserExtract.getExtractType());
            map.put("银行卡", yxUserExtract.getBankCode());
            map.put("开户地址", yxUserExtract.getBankAddress());
            map.put("支付宝账号", yxUserExtract.getAlipayCode());
            map.put("提现金额", yxUserExtract.getExtractPrice());
            map.put(" mark", yxUserExtract.getMark());
            map.put(" balance", yxUserExtract.getBalance());
            map.put("无效原因", yxUserExtract.getFailMsg());
            map.put(" failTime", yxUserExtract.getFailTime());
            map.put("-1 未通过 0 审核中 1 已提现", yxUserExtract.getStatus());
            map.put("微信号", yxUserExtract.getWechat());
            list.add(map);
        }
        FileUtil.downloadExcel((List)list, response);
    }
    
    @Transactional(rollbackFor = { Exception.class })
    public void doExtract(final UserExtract resources) {
        if (resources.getStatus() == null) {
            throw new BadRequestException("请选择审核状态");
        }
        if (ShopCommonEnum.EXTRACT_0.getValue().equals(resources.getStatus())) {
            throw new BadRequestException("请选择审核状态");
        }
        final UserExtract userExtract = (UserExtract)this.getById((Serializable)resources.getId());
        if (!ShopCommonEnum.EXTRACT_0.getValue().equals(userExtract.getStatus())) {
            throw new BadRequestException("该申请已经处理过啦！");
        }
        if (ShopCommonEnum.EXTRACT_MINUS_1.getValue().equals(resources.getStatus())) {
            if (StrUtil.isEmpty((CharSequence)resources.getFailMsg())) {
                throw new BadRequestException("请填写失败原因");
            }
            final String mark = "提现失败,退回佣金" + resources.getExtractPrice() + "元";
            final ShopUser shopUser = (ShopUser)this.userService.getById((Serializable)resources.getUid());
            final double balance = NumberUtil.add((Number)shopUser.getBrokeragePrice(), (Number)resources.getExtractPrice()).doubleValue();
            this.billService.income(resources.getUid(), "提现失败", BillDetailEnum.CATEGORY_1.getValue(), BillDetailEnum.TYPE_4.getValue(), resources.getExtractPrice().doubleValue(), balance, mark, resources.getId().toString());
            this.userService.incBrokeragePrice(resources.getExtractPrice(), resources.getUid());
            resources.setFailTime(new Date());
        }
        else {
            final TemplateBean templateBean = TemplateBean.builder().extractId(resources.getId()).templateType(TemplateListenEnum.TYPE_8.getValue()).build();
            this.publisher.publishEvent((ApplicationEvent)new TemplateEvent(this, templateBean));
        }
        this.saveOrUpdate(resources);
    }
    
    public UserExtractServiceImpl(final IGenerator generator, final UserExtractMapper userExtractMapper, final UserService userService, final UserBillService billService, final ApplicationEventPublisher publisher) {
        this.generator = generator;
        this.userExtractMapper = userExtractMapper;
        this.userService = userService;
        this.billService = billService;
        this.publisher = publisher;
    }
}
